/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.smarttmt.idu.web.beans;


import com.smarttmt.idu.web.utilities.FacesUtils;
import java.io.Serializable;
import java.util.LinkedHashMap;
import java.util.Locale;
import java.util.Map;
import javax.annotation.PostConstruct;
import javax.enterprise.context.SessionScoped;

import javax.faces.context.FacesContext;
import javax.faces.event.ValueChangeEvent;
import javax.inject.Named;

/**
 *
 * @author davismaster
 */

@Named(value = "languaje")
@SessionScoped
public class LocalesBean  implements Serializable {

    private static final long serialVersionUID = 1L;
    private String localeCode;
    private static final Map<String, Object> countries;

    static {
        countries = new LinkedHashMap<>();
        countries.put("Español (Latinoamérica)‬",new Locale("es"));
        countries.put("English (United States)‬",Locale.ENGLISH); //label, value

    }

    @PostConstruct
    public void init() {

        if (FacesUtils.getValueFromSession("newLocalValue") != null) {
            String newLocalValue = (String) FacesUtils.getValueFromSession("newLocalValue");
            this.localeCode = newLocalValue;
            for (Map.Entry<String, Object> entry : countries.entrySet()) {

                if (entry.getValue().toString().equals(this.localeCode)) {
                    FacesContext.getCurrentInstance()
                            .getViewRoot().setLocale((Locale) entry.getValue());
                    FacesUtils.putValueInSession("newLocalValue", this.localeCode);
                }
            }
            
            System.err.println("lenguaje 1"+this.localeCode);

        }else{
            this.localeCode=FacesContext.getCurrentInstance().getViewRoot().getLocale().getLanguage();
            System.err.println("lenguaje 2"+this.localeCode);
        }
            

    }

    public Map<String, Object> getCountriesInMap() {
        return countries;
    }

    public String getLocaleCode() {
        return localeCode;
    }

    public void setLocaleCode(String localeCode) {
        this.localeCode = localeCode;
    }

    //value change event listener
    public void countryLocaleCodeChanged(ValueChangeEvent e) {

        String newLocaleValue = e.getNewValue().toString();

        //loop country map to compare the locale code
        for (Map.Entry<String, Object> entry : countries.entrySet()) {

            if (entry.getValue().toString().equals(newLocaleValue)) {
                FacesContext.getCurrentInstance()
                        .getViewRoot().setLocale((Locale) entry.getValue());
                FacesUtils.putValueInSession("newLocalValue", newLocaleValue);
            }
        }
    }
    // Add business logic below. (Right-click in editor and choose
    // "Insert Code > Add Business Method")
}
